package teleradiologia.web;

import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import teleradiologia.domain.Person;
import teleradiologia.service.PersonManipulator;

@Controller
public class AccountController {
	private PersonManipulator personManipulator;

	private org.springframework.security.providers.encoding.BaseDigestPasswordEncoder encoder = new Md5PasswordEncoder();
	private static final Log log = LogFactory.getLog(AccountController.class);

	public PersonManipulator getPersonManipulator() {
		return personManipulator;
	}

	public void setPersonManipulator(PersonManipulator personManipulator) {
		this.personManipulator = personManipulator;
	}

	public AccountController() {
	}

	@RequestMapping("/account/changePasswordHome.htm")
	public ModelAndView handleChangePasswordHome() {
		return new ModelAndView("account/changePassword");
	}

	@RequestMapping("/account/changePassword.htm")
	public ModelAndView handleChangePassword(
			@RequestParam("currentPassword") String currentPassword,
			@RequestParam("newPassword") String newPassword,
			@RequestParam("repeatNewPassword") String repeatNewPassword) {

		HashMap<String, Object> model = new HashMap<String, Object>();

		Person me = ((Person) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal());

		me = personManipulator.getById(me.getId());

		/**
		 * 1. czy stare haslo jest poprawne
		 * 2. czy nowe hasla sie zgadzaja
		 * 3. zmiana hasla
		 */

		log.info(me.getPassword() + " " + encoder.encodePassword(currentPassword, me.getUsername()));



		if(encoder.encodePassword(currentPassword, me.getUsername()).equals(me.getPassword())
				&& newPassword.equals(repeatNewPassword)) {

			me.setPassword(newPassword);

			personManipulator.update(me);

			model.put("success", "true");
		} else {
			model.put("error", "true");
		}

		return new ModelAndView("account/changePassword", "model", model);
	}

}
